const mongoose = require("../db");
const Schema = mongoose.Schema;

const opportunitySchema = new Schema({
  opportunityId: { type: String, unique: true, required: true },
  customerId: { type: mongoose.Schema.Types.ObjectId, ref: 'Customer' },
  leadId: { type: mongoose.Schema.Types.ObjectId, ref: 'Lead' },
  title: { type: String, required: true },
  value: { type: Number, required: true, min: 0 },
  stage: { 
    type: String, 
    enum: ['初步接触', '需求确认', '方案提供', '合同谈判', '成交', '失败'], 
    default: '初步接触' 
  },
  probability: { type: Number, min: 0, max: 100, default: 10 },
  expectedCloseDate: { type: Date },
  assignedTo: { type: mongoose.Schema.Types.ObjectId, ref: 'Admin' },
  status: { 
    type: String, 
    enum: ['进行中', '成交', '失败'], 
    default: '进行中' 
  },
  createTime: { type: Date, default: Date.now },
  updateTime: { type: Date, default: Date.now }
});

// 创建索引
opportunitySchema.index({ opportunityId: 1 });
opportunitySchema.index({ customerId: 1 });
opportunitySchema.index({ leadId: 1 });
opportunitySchema.index({ assignedTo: 1 });
opportunitySchema.index({ stage: 1 });
opportunitySchema.index({ status: 1 });
opportunitySchema.index({ value: -1 });
opportunitySchema.index({ expectedCloseDate: 1 });
opportunitySchema.index({ createTime: -1 });

// 更新时间中间件
opportunitySchema.pre('save', function(next) {
  this.updateTime = new Date();
  next();
});

opportunitySchema.pre('findOneAndUpdate', function(next) {
  this.set({ updateTime: new Date() });
  next();
});

// 根据阶段自动更新成交概率
opportunitySchema.pre('save', function(next) {
  const stageProbability = {
    '初步接触': 10,
    '需求确认': 25,
    '方案提供': 50,
    '合同谈判': 75,
    '成交': 100,
    '失败': 0
  };
  
  if (this.isModified('stage') && stageProbability[this.stage] !== undefined) {
    this.probability = stageProbability[this.stage];
  }
  
  next();
});

module.exports = mongoose.model("Opportunity", opportunitySchema);